package com.example.tetstmybatis.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.tetstmybatis.domain.User2;
import com.example.tetstmybatis.domain.User_sb;
import com.example.tetstmybatis.req.*;
import com.example.tetstmybatis.resp.CommonResp;
import com.example.tetstmybatis.resp.User2LoginResp;
import com.example.tetstmybatis.service.User2Service;
import com.example.tetstmybatis.utils.SnowFlake;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
public class User2Controller {
    @Resource
    private User2Service user2Service;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SnowFlake snowFlake;
    @Resource
    private User_sbController user_sbController;


    @PostMapping("/login")
    public CommonResp login(@RequestBody User2LoginReq req) {
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        //md5加密
        CommonResp<User2LoginResp> resp = new CommonResp<>();
        User2LoginResp user2LoginResp = user2Service.login(req);
        if (ObjectUtils.isEmpty(user2LoginResp)) {
            resp.setSuccess(false);
            return resp;
        } else {
            Long token = snowFlake.nextId();//生成用户token
            System.out.println(token.toString());
            user2LoginResp.setToken(token.toString());//将用户的token信息返回给请端
            resp.setContent(user2LoginResp);
            redisTemplate.opsForValue().set(JSONObject.toJSONString(token), JSONObject.toJSONString(user2LoginResp),3600*24,TimeUnit.SECONDS);
            return resp;
        }
    }

    @PostMapping("/register")
    public CommonResp reg( @RequestBody User2RegisterReq req){
        CommonResp resp = new CommonResp<>();
        //对密码进行加密
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        User2 user2Db = user2Service.selectByLoginName(req.getLoginName());
        if(ObjectUtils.isEmpty(user2Db)){
            //该注册名不存在
            boolean register = user2Service.register(req);
            if(register){
                //添加成功
                resp.setSuccess(true);
            }else {
                //添加失败;
                resp.setSuccess(false);
            }

        }else {
            //该注册用户名已存在
            resp.setSuccess(false);
//            return resp;
        }
        return resp;
    }

    @GetMapping("/listall")
    public CommonResp listall( User2QueryReq req){
        CommonResp list = user2Service.listall(req);
        return  list;
    }
    @RequestMapping(value = "/rubbish", method = { RequestMethod.POST,RequestMethod.GET})
    public String rubbish(HttpServletRequest request, HttpServletResponse response){
        String index=null;
        MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
        MultipartFile multipartFile =  req.getFile("file");
        String user=request.getParameter("user");
        String realPath = "D:\\python Rubbish\\temp\\data";//存放目录
        try {
            File dir= new File(realPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File file = new File(realPath, "temp.jpg");
            multipartFile.transferTo(file);
            try {
                String[] args1 = new String[] { "C:\\Users\\twy\\anaconda3\\python.exe", "D:\\Users\\twy\\Desktop\\test.py"};
                Process proc = Runtime.getRuntime().exec(args1);// 执行py文件
                BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                    index=line;
                }
                in.close();
                proc.waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return index;
    }

    @RequestMapping(value = "/weChat", method = { RequestMethod.POST,RequestMethod.GET})
    public String uploadImage(HttpServletRequest request, HttpServletResponse response){
        int i=0;
        MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
        MultipartFile multipartFile =  req.getFile("file");
        String user=request.getParameter("user");
        String realPath = "D:\\image\\temp";
        try {
            File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            File file  =  new File(realPath,date+"-name-"+user+".jpg");
            System.out.println(file);
            multipartFile.transferTo(file);
            try {
                String[] args1 = new String[] { "C:\\Users\\twy\\anaconda3\\python.exe", "D:\\Users\\twy\\Desktop\\人脸识别.py", String.valueOf(file)};
                Process proc = Runtime.getRuntime().exec(args1);// 执行py文件
                BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                    if (line.equals("pass"))
                    {
                        i=1;
                    }
                    if(line.equals("NO"))
                    {
                        i=-1;
                    }
                    if(line.equals("not face"))
                    {
                        i=-2;
                    }
                }
                System.out.println(i);
                in.close();
                proc.waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        System.out.println(i);
        if(i==1)
        {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
            User_sb user_sb=new User_sb();
            user_sb.setWxName(user);
            user_sbController.update(user_sb);
            return date;
        }
        else if(i==-1)
        {
            return "签到失败";
        }
        else if(i==-2)
        {
            return "未识别到人脸";
        }
        else
        {
            return "网诺错误";
        }
    }


}
